package com.sunagy.demand.front.service.impl;

import com.sunagy.demand.front.config.MazConfig;
import com.sunagy.demand.front.config.WXConfig;
import com.sunagy.demand.front.dataobject.AdminAuthToken;
import com.sunagy.demand.front.dataobject.AdminUser;
import com.sunagy.demand.front.dto.AdminUserDto;
import com.sunagy.demand.front.exception.TokenExpiredException;
import com.sunagy.demand.front.exception.TokenNotFoundException;
import com.sunagy.demand.front.repository.AdminAuthTokenRepository;
import com.sunagy.demand.front.security.SecurityUserDetails;
import com.sunagy.demand.front.service.AdminAuthTokenService;
import com.sunagy.demand.front.utils.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/4/25
 * time：上午11:26
 */
@Service
public class AdminAuthTokenServiceImpl implements AdminAuthTokenService {

    @Autowired
    private MazConfig mazConfig;

    @Autowired
    private AdminAuthTokenRepository adminAuthTokenRepository;

    @Override
    public SecurityUserDetails validToken(String token) {
        SecurityUserDetails securityUserDetails = new SecurityUserDetails();
        AdminAuthToken adminAuthToken = adminAuthTokenRepository.findByToken(token);
        if (adminAuthToken == null){
            throw new TokenNotFoundException();
        }
        if ((new Date()).compareTo(adminAuthToken.getToken_exptime()) > 0 ? true : false){
            throw new TokenExpiredException();
        }
        long currentTime = System.currentTimeMillis();
        currentTime +=mazConfig.getTokenExpireTime();
        Date date=new Date(currentTime);
        adminAuthToken.setToken_exptime(date);
        adminAuthTokenRepository.save(adminAuthToken);
        securityUserDetails.setUserId(adminAuthToken.getUserid());
        securityUserDetails.setToken(token);
        return securityUserDetails;
    }

    @Override
    @Transactional
    public String updateToken(AdminUserDto adminUserDto) {
        long currentTime = System.currentTimeMillis();
        currentTime +=mazConfig.getTokenExpireTime();
        Date date=new Date(currentTime);
        AdminAuthToken adminAuthToken = adminAuthTokenRepository.findByUserid(adminUserDto.getId());
       if (adminAuthToken == null){
           adminAuthToken = new AdminAuthToken();
           adminAuthToken.setEnable(true);
           adminAuthToken.setUser_type(1);
           adminAuthToken.setUserid(adminUserDto.getId());
           String token = EncryptUtil.md5(adminUserDto.getId() + adminUserDto.getUsername() + adminUserDto.getPassword());
           adminAuthToken.setToken(token);
       }
        adminAuthToken.setToken_exptime(date);
        adminAuthTokenRepository.save(adminAuthToken);
        return adminAuthToken.getToken();
    }
}
